<template>
	<view class="warpper">
		<u-navbar
			:title="$t('order.Initiate-Consignment')"
			bgColor="#ffffff"
			@leftClick="goback"
			titleStyle="font-size: 32rpx;font-weight: 500;color: #000000;"
			placeholder
		></u-navbar>


		<view class="content">
			<view class="line-cell">
				<view class="line-cell__left">
					{{ $t('order.Sell-Currency') }}
				</view>
				<view
					class="line-cell__right"
					:class="{ disabled: isEdit }"
					@click="
						() => {
							SelectPopupShow = true;
						}
					"
				>
					<view class="line-cell__right__text">
						{{ currencyLabel }}
					</view>
					<view class="iconfont icon-jiantou-you line-cell__right__icon"></view>
				</view>
			</view>

			<view class="line-cell">
				<view class="line-cell__left">
					{{ $t('order.Sales-Quantity') }}
				</view>
				<view class="line-cell__right" :class="{ disabled: isEdit }">
					<u--input
						type="digit"
						:placeholder="$t('order.Please-Enter')"
						border="none"
						v-model="releaseTradeForm.totalStock"
						@blur="handleBlur(releaseTradeForm.totalStock)"
						inputAlign="right"
					></u--input>
					<view class="line-cell__right__text">
						{{ currencyLabel }}
					</view>
				</view>
			</view>

			<view class="line-cell">
				<view class="line-cell__left">
					{{ $t('order.Recipient-Country') }}
				</view>
				<view
					class="line-cell__right"
					@click="
						() => {
							SelectCountryShow = true;
						}
					"
					:class="{ disabled: isEdit }"
				>
					<view class="line-cell__right__text" :class="{ 'thin-text': !releaseTradeForm.recipientCountry }">
						{{ releaseTradeForm.recipientCountry ? $t('order.' + releaseTradeForm.recipientCountry) : $t('order.Please-Choose') }}
					</view>

					<view class="iconfont icon-jiantou-you line-cell__right__icon"></view>
				</view>
			</view>
		</view>

		<view class="content padding-box">
			<view class="title">
				{{ $t('order.Receipt-Account') }}
			</view>
			<u--textarea :placeholder="$t('order.CashOut-tips1')" border="none" height="80rpx" v-model="receiptAccountValue"></u--textarea>
		</view>

		<view class="bottom-box">
			<view class="bottom-box__tips">
				<view class="">
					{{ $t('order.CashOut-tips2') }}
				</view>
				<view class="">
					{{ $t('order.CashOut-tips3') }}
				</view>
			</view>
			<u-button class="bottom-box__btn" @click="nextHandle" :loading="isLoading" :loadingText="$t('order.Sell')">
				{{ $t('order.Sell') }}
			</u-button>
		</view>

		<!-- 选择货币弹窗 -->
		<SelectPopup
			:show.sync="SelectPopupShow"
			:option="currencyOption"
			:title="$t('order.currency')"
			:value="releaseTradeForm.sourceCurrency"
			@finish="onChangeCurrency"
			v-if="SelectPopupShow"
			labelSigned="currency"
			valueSigned="id"
		></SelectPopup>
		<!-- 选择国家弹窗 -->
		<SelectPopup
			:show.sync="SelectCountryShow"
			:option="CountryOption"
			:title="$t('order.Country')"
			:value="releaseTradeForm.recipientCountry"
			@finish="onChangeCountry"
			v-if="SelectCountryShow"
		></SelectPopup>
	</view>
</template>

<script>
import { releaseTradeOrder, getCurrencyList, releaseOderAddress, getOderAddress, editTradeOrder, setShelfStatus } from '@/services/bourse.js';
import SelectPopup from '@/components/SelectPopup.vue';
import { mapState } from 'vuex';
import { getWalletList } from '@/services/user.js';

export default {
	data() {
		return {
			tabType: 'danren',
			tabType: 'duoren',
			receiptAccountValue: '',
			walletList: [],
			releaseTradeForm: {
				tradeScene: 1,
				tradeType: 0,
				tradeDescription: 'OTC交易',
				sourceCurrency: 1,
				totalStock: '',
				tradeAddressId: '',
				shelfStatus: 1, //	上架状态
				recipientCountry: '',
				exchangeDetailList: [
					{
						targetCurrencyId: 1,
						targetPrice: 1
					}
				]
			},
			currencyOption: [],
			SelectPopupShow: false,
			SelectCountryShow: false,
			isEdit: 0,
			isLoading: false,
		};
	},

	computed: {
		...mapState(['currentOrderInfo']),
		currencyLabel() {
			const arr = this.currencyOption?.filter((t) => t.id == this.releaseTradeForm.sourceCurrency);
			if (arr.length > 0) {
				return arr[0].currency;
			} else {
				return '';
			}
		},

		CountryOption() {
			return [
				{
					label: this.$t('order.China'),
					value: 'China'
				},
				{
					label: this.$t('order.Russia'),
					value: 'Russia'
				}
			];
		}
	},
	components: {
		SelectPopup
	},
	onLoad(option) {
		if (option.isEdit) {
			this.isEdit = option.isEdit;
			this.editHandle();
		}
		// this._getCurrencyList();
		this.getWalletListData();
	},
	// 监听页面返回
	onBackPress(options) {
		if (options.from === 'navigateBack') {
			return false;
		}
		this.goBack();
		return true;
	},
	methods: {
	
		handleSwitchTab(index) {
			this.tabIndex = index;
		},
		goback() {
			if (this.isEdit) {
				this._setShelfStatus();
			}
			// uni.navigateBack()
			uni.redirectTo({
				url: '/pagesUser/bourse/release'
			});
		},
		async getWalletListData() {
			var { result } = await getWalletList();
			this.walletList = result.rows;
			this.currencyOption = [...result.rows];
			this.currencyOption = this.currencyOption.filter((i) => {
				return i.currencyVo.isOpen == 1 && i.currencyVo.tradeOpen == 1;
			});
			this.currencyOption = this.currencyOption.map((it) => {
				return {
					...it,
					currency: it.currencyVo.currency,
					id: it.currencyVo.id
				};
			});
			console.log('this.currencyOption', this.currencyOption);
		},
		// 返回要重新上架
		async _setShelfStatus() {
			const { success } = await setShelfStatus({
				tradeId: this.currentOrderInfo.tradeId,
				shelfStatus: 1
			});
		},
		handleBlur(val) {
			try {
				// 限制小数点后四位
				if (val.includes('.')) {
					//小数点后的位数
					let numAfterDot = val.toString().split('.')[1].length;
					//小数点前的位数
					let numBeforeDot = val.toString().split('.')[0].length;
					//最大长度等于小数点前的位数+3（小数点加小数点后两位）
					this.maxlength = numBeforeDot + 5;
					//小数点后的位数大于2，截取
					if (numAfterDot > 4) {
						this.releaseTradeForm.totalStock = val.substr(0, numBeforeDot + 5);
					}
				}
			} catch (e) {
				//TODO handle the exception
			}

			console.log('val', val, this.filterList(this.releaseTradeForm.sourceCurrency));
			if (val > this.filterList(this.releaseTradeForm.sourceCurrency)) {
				this.releaseTradeForm.totalStock = this.filterList(this.releaseTradeForm.sourceCurrency);

				return;
			}
		},
		filterList(val) {
			var data = this.walletList.filter((t) => t.currencyVo?.isOpen == 1 && t.currencyId == val);

			return parseFloat(data[0]?.amount);
		},
		// 若为编辑,则回调表单
		async editHandle() {
			const { success, result } = await getOderAddress(this.currentOrderInfo.tradeAddressId);
			this.releaseTradeForm = {
				tradeId: this.currentOrderInfo.tradeId,
				tradeScene: this.currentOrderInfo.tradeScene,
				tradeType: this.currentOrderInfo.tradeType,
				tradeDescription: this.currentOrderInfo.tradeDescription,
				sourceCurrency: this.currentOrderInfo.sourceCurrency,
				totalStock: this.currentOrderInfo.totalStock,
				tradeAddressId: this.currentOrderInfo.tradeAddressId,
				shelfStatus: this.currentOrderInfo.shelfStatus, //	上架状态
				recipientCountry: this.currentOrderInfo.recipientCountry,
				exchangeDetailList: [
					{
						targetCurrencyId: this.currentOrderInfo.exchangeDetailList[0].targetCurrencyId,
						targetPrice: this.currentOrderInfo.exchangeDetailList[0].targetPrice
					}
				]
			};
			this.receiptAccountValue = result.data.content;
		},
		// async _getCurrencyList() {
		// 	const {
		// 		success,
		// 		result
		// 	} = await getCurrencyList()
		// 	if (success) {
		// 		console.log('result.data',result.data);
		// 		this.currencyOption = result.data.filter(i=>i.tradeOpen==1)
		// 		console.log(this.currencyOption);
		// 	}
		// },
		// 选择货币回调
		onChangeCurrency(val) {
			this.releaseTradeForm.exchangeDetailList[0].targetCurrencyId = val;
			this.releaseTradeForm.sourceCurrency = val;
		},
		// 选择国家回调
		onChangeCountry(val) {
			this.releaseTradeForm.recipientCountry = val;
		},
		// 点击发布回调
		async nextHandle() {
			const { success, msg } = this.verifyForm();
			if (success) {
				this.isLoading = true;
				const res = await releaseOderAddress({
					content: this.receiptAccountValue
				});
				if (res.success) {
					// 编辑模式
					if (this.isEdit) {
						const obj = {
							tradeId: this.releaseTradeForm.tradeId,
							tradeAddressId: res.result.data,
							shelfStatus: 1
						};
						this.releaseTradeForm.tradeAddressId = res.result.data;
						const resq = await editTradeOrder(obj);
						if (resq.success) {
							uni.showToast({
								title: this.$t('order.edited-successfully'),
								duration: 2000,
								icon: 'none'
							});
							uni.navigateBack();
						}
					} else {
						this.releaseTradeForm.tradeAddressId = res.result.data;
						const resq = await releaseTradeOrder(this.releaseTradeForm);
						if (resq.success) {
							uni.showToast({
								title: this.$t('order.Published-successfully'),
								duration: 2000,
								icon: 'none'
							});
							uni.navigateBack({
								delta: 2
							});
						}
					}
				}
				this.isLoading = false;
			} else {
				uni.showToast({
					title: msg,
					duration: 2000,
					icon: 'none'
				});
			}
		},
		// 验证表单
		verifyForm() {
			let res = {
				success: true,
				msg: ''
			};
			if (this.releaseTradeForm.totalStock == '' || this.releaseTradeForm.totalStock == 0) {
				res.success = false;
				res.msg = this.$t('order.verify-tips1');
				return res;
			}

			if (this.releaseTradeForm.recipientCountry == '') {
				res.success = false;
				res.msg = this.$t('order.verify-tips2');
				return res;
			}
			this.receiptAccountValue = this.receiptAccountValue.trim();
			if (this.receiptAccountValue == '') {
				res.success = false;
				res.msg = this.$t('order.verify-tips3');
				return res;
			}

			return res;
		}
	}
};
</script>

<style lang="scss" scoped>

.disabled {
	pointer-events: none !important;
	opacity: 0.4;
}

.warpper {
	.content {
		margin: 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
		padding: 0 20rpx;
		background: #ffffff;

		& > view:last-child {
			box-shadow: none;
		}

		.line-cell {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 112rpx;
			background: #ffffff;
			box-shadow: inset 0px -2rpx 0px 0px rgba(0, 0, 0, 0.05);
			font-size: 28rpx;
			font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
			font-weight: 400;
			color: #000000;

			&__right {
				max-width: 320rpx;
				display: flex;
				align-items: center;

				&__text {
					margin-left: 10rpx;
				}

				.thin-text {
					color: rgba(0, 0, 0, 0.3);
				}

				.deep-text {
					color: #fe6600;
				}

				&__icon {
					font-size: 30rpx;
					color: rgba(0, 0, 0, 0.2);
					margin-left: 6rpx;
				}
			}
		}
	}

	.padding-box {
		padding: 36rpx 20rpx;

		.title {
			margin-bottom: 30rpx;
		}

		/deep/.u-textarea {
			padding: 0;
			min-height: 80rpx;
		}
	}

	.bottom-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 750rpx;
		background-color: #ffffff;

		&__tips {
			font-size: 28rpx;
			font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.3);
			line-height: 40rpx;
			padding: 10rpx 30rpx;
			background-color: #f6f6f6;
		}

		&__btn {
			margin: 10rpx 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 690rpx;
			height: 80rpx;
			color: #ffffff;
			background: #61bdb2;
			border-radius: 80rpx;
		}
	}
}
</style>
